//
//  UITextView+Placeholder.m
//  SleepingElf
//
//  Created by karong on 2023/6/27.
//

#import "UITextView+Placeholder.h"

NSString *const GRPlaceHolderLabelKey =  @"GRPlaceHolderLabelKey";


@implementation UITextView (Placeholder)

- (void)layoutSubviews {
    [super layoutSubviews];
    self.placeholderLabel.textColor = UIColor.font_gray_727584;
}

- (UILabel *)placeholderLabel
{
    UILabel *label = objc_getAssociatedObject(self, &GRPlaceHolderLabelKey);
    return label;
}

- (void)setPlaceholderLabel:(UILabel *)placeholderLabel
{
    objc_setAssociatedObject(self, &GRPlaceHolderLabelKey, placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)placeholderText
{
    NSString *text = self.placeholderLabel.text;
    return text;
}

- (void)setPlaceholderText:(NSString *)placeholderText
{
    if (placeholderText != nil && self.placeholderLabel == nil) {
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.textColor = UIColor.font_gray_727584;
        label.font = [UIFont systemFontOfSize:14];
        [self insertSubview:label atIndex:0];
        self.placeholderLabel = label;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textChanged)
                                                     name:UITextViewTextDidChangeNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textChanged)
                                                     name:UITextViewTextDidBeginEditingNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(textChanged)
                                                     name:UITextViewTextDidEndEditingNotification
                                                   object:nil];

        NSTextContainer *textContainer = self.textContainer;
        UIEdgeInsets textContainerInset = self.textContainerInset;
        CGFloat left = textContainerInset.left + textContainer.lineFragmentPadding;
        [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(left);
            make.right.equalTo(self);
            make.top.equalTo(self).offset(textContainerInset.top);
        }];
    }
    
    self.placeholderLabel.text = placeholderText;
    [self.placeholderLabel sizeToFit];
}

- (void)textChanged
{
    BOOL hidden = self.text.length > 0;
    self.placeholderLabel.hidden = hidden;
}

@end
